#! /bin/sh

vim_exec="/Applications/mvim "


get_desktop_resolution()
{
	local res=`osascript -e 'tell application "Finder" to get the bounds of window of desktop' | awk -F "," '{ print $3 $4 }'`
	desktop_resolution=($res)
}

get_vim_window_size()
{
	#/Applications/MacVim.app/Contents/MacOS/Vim -g &
	#local vim_pid=$!
	#echo $vim_pid
	#local size=`osascript -e 'tell application "MacVim" to get the bounds of the front window' | awk -F "," '{ print $3-$1 " " $4-$2 }'`
	#vim_window_size=($size)
	#kill $vim_pid

	vim_window_size=(860 600)
}

get_vim_window_position()
{
	get_desktop_resolution
	get_vim_window_size

	local margin=($(( (desktop_resolution[0] - (vim_window_size[0] * 2)) / 3 )) $(( (desktop_resolution[1] - (vim_window_size[1] * 2)) / 3 )))
	local half=($(( desktop_resolution[0] / 2 )) $(( desktop_resolution[1] / 2 )))

	case "$1" in
		"1")	winpos=(${margin[0]} ${margin[1]})
		;;
		"2")	winpos=($(( half[0] + (margin[0] / 2) )) ${margin[1]})
		;;
		"3")	winpos=(${margin[0]} $(( half[1] + (margin[1] / 2) )))
		;;
		"4")	winpos=($(( half[0] + (margin[0] / 2) )) $(( half[1] + (margin[1] / 2) )))
		;;
		"5")	winpos=($(( half[0] - (vim_window_size[0] / 2) )) $(( half[1] - (vim_window_size[1] / 2) )))
		;;
	esac
}

get_vim_window_position_keyseq()
{
	get_vim_window_position $1
	if [ "$winpos" != "" ]; then
		poskeyseq="<C-\><C-N>:winpos ${winpos[0]} ${winpos[1]}<CR>"
	fi
}

is_open()
{
	isopen=`$vim_exec --serverlist | grep -i "$1" | wc -l`
	isopen=${isopen// }
}


check_param()
{
	if [ "$1" == "" ]; then
		show_help "$2"
	fi
}

show_help()
{
	if [ "$1" != "" ]; then
		echo error: $*
	fi
	echo "$0 <instance name> <command>"
	echo "command:"
	echo "   open <filename> [<position index>]"
	echo "   save"
	echo "   close"
	echo "   pos <position index>"
	exit 1
}


# main
check_param $1 "missing <instance name>"
instance="--servername $1 "

is_open $1

case "$2" in
	"open")		check_param $3 "missing <filename> for OPEN"
				filename=$3
	;;
	"save")		keyseq="<C-\><C-N>:up<CR>"
	;;
	"close")	keyseq="<C-\><C-N>:q<CR>"
	;;
	"pos")		check_param $3 "missing <position index> for POS"
				get_vim_window_position_keyseq $3
				keyseq=$poskeyseq
	;;
	*)			show_help "unknown <command>"
	;;
esac



if [ "$filename" != "" ]; then
	$vim_exec $instance --remote-silent $filename
	if [ "$4" != "" -a "$isopen" == "0" ]; then
		get_vim_window_position_keyseq $4
		sleep 0.3 # wait for open
		$vim_exec $instance --remote-send "$poskeyseq"
	fi
elif  [ "$keyseq" != "" ]; then
	if [ "$isopen" != "0" ]; then
		$vim_exec $instance --remote-send "$keyseq"
	fi
fi
